/**
 * @param {number[][]} matrix
 * @return {number[]}
 */
var spiralOrder = function (matrix) {
  if (matrix.length === 0) return [];

  const result = [];
  let top = 0, bottom = matrix.length - 1;
  let left = 0, right = matrix[0].length - 1;

  while (top <= bottom && left <= right) {
    // 从左到右遍历顶部行
    for (let i = left; i <= right; i++) {
      result.push(matrix[top][i]);
    }
    top++; // 顶部边界下移

    // 从上到下遍历右侧列
    for (let i = top; i <= bottom; i++) {
      result.push(matrix[i][right]);
    }
    right--; // 右侧边界左移

    // 检查是否还有剩余行和列
    if (top > bottom || left > right) break;

    // 从右到左遍历底部行
    for (let i = right; i >= left; i--) {
      result.push(matrix[bottom][i]);
    }
    bottom--; // 底部边界上移

    // 从下到上遍历左侧列
    for (let i = bottom; i >= top; i--) {
      result.push(matrix[i][left]);
    }
    left++; // 左侧边界右移
  }

  return result;
};